<?php
//require_once('../../../wp-load.php');
require_once('includes/class.phpmailer.php');
require_once('includes/simplepie.inc');
require_once('accs-communication-system.php');


function accs_announcement($title, $content)
{
	$a[] = '<tr><td valign="top" bgcolor="#c8bb8a">';
	$a[] = '<span style="font-family:Arial;font-size:1em; font-weight:bold; display:block;">';
	$a[] = $title;
	$a[] = '</span>';
	$a[] = $content;
	$a[] = '</td></tr>';
	return $a;
}


function accs_event($title, $content){
	$e[] = '<tr><td valign="top" style="font-family:arial, sans-serif; font-weight:normal; font-size:1em; padding-bottom:3px;">';
	$e[] = '<span style="font-size:1em; font-weight:bold; display:block; padding-bottom:5px;">';
	$e[] = $title;
	$e[] = '</span>';
	$e[] = $content;
	$e[] = '</td></tr>';
	return $e;

}


function accs_promotion($title, $content){
	$p[] = '<tr><td valign="top" bgcolor="#c8bb8a">';
	$p[] = '<span style="font-family:Arial;font-size:1em; font-weight:bold; display:block;">';
	$p[] = $title;
	$p[] = '</span>';
	$p[] = $content;
	$p[] = '</td></tr>';
	return $p;
}

function accs_get_user_content($user, $type){
	global $wpdb, $post;
	$meta_key_date = 'accs-dates';		
	$date = date('Y-m-d');
	$week = date('W') + 1;	//Looking to next week
			
	$user_cats = get_user_meta( $user->ID, ACCS_SUBSCRIPTION_KEY,true ); 
	$user_req =  get_option(ACCS_PREFIX . 'REQUIRED_SUBSCRIPTION_CATEGORIES');
	$user_aud = get_user_meta( $user->ID, ACCS_AUDIENCE_KEY,true ); 
	
	$categories = null;
	if(count($user_cats) > 0){
		$categories = array_merge($user_cats, $user_req);
	}
	else{
		$categories = $user_req;
	}

	$args =  array(
		'post_status' => array('publish','future'),
		'category_name' => implode(',',$categories),
		'audience' => implode(',',$user_aud)
	);

	if($type == 'daily'){	
		
		$args = array_merge
			($args, array(
					'meta_query' => array(
						array(
							'key' => $meta_key_date,
							'value' => $date,
							'compare' => 'LIKE'
						)
					)
			)
		);
	}
	else if($type == 'weekly'){
	
		$args = array_merge($args, array('w' => $week));
	}
	else{
		throw new Exception();
	}

	//Event query
	$e_args = array_merge($args, array('post_type' => 'accs_event'));
 	
 	//Announcement query
 	$a_args = array_merge($args, array('post_type' => 'accs_announcement'));
 	
 	//Promo query
	$p_args = array_merge($args, array('post_type' => 'accs_promo'));

	$e_nodata = array((object) array(
	  'post_title' => 'No Events',
	  'post_type' => 'accs_event',
	  'post_content' => ''
	));  	
	$p_nodata =array( (object)array(
	  'post_title' => 'No Promotions',
	  'post_type' => 'accs_promo',
	  'post_content' => ''
	));  	
	$a_nodata =array( (object)array(
	  'post_title' => 'No Announcements',
	  'post_type' => 'accs_announcement',
	  'post_content' => ''
	));  	
	
	$e_content = query_posts( $e_args );
	$a_content = query_posts( $a_args );
	$p_content = query_posts( $p_args );
	
	if(count($e_content) == 0)
	{
		$e_content = $e_nodata;
	}
	
	if(count($a_content) == 0)
	{
		$a_content = $a_nodata;
	}
	
	if(count($p_content) == 0)
	{
		$p_content = $p_nodata;

	}	

	$content  =array_merge( $a_content,$e_content,$p_content);
	return  $content;

}

function get_the_accs_excerpt($content){
	$filtered = substr($content, 0, 200);
	$index = strpos($filtered, ' ');
	return substr($filtered, 0, $index);
}


function accs_get_email_content($user, $type){
	
	//URL generated plugin should not be dependent on other dependencies like having the right image in the upload folder or 
	//even the right theme installed. Should be self contained to remove dependencies that can break over time.
	$url = site_url();
	$logo = 'http://rollins-capstone-project.googlecode.com/files/Rollins_Horizontal_Small.png';
	$header = 'Good Morning, Rollins!';

	if($type == 'weekly'){
		$header = 'This Week At Rollins!';
	}
	//$url . '/wp-content/plugins/'. ACCS_PLUGIN_DIR .'/resources/Rollins_Horizontal.png';

	$message[] = '<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><style>a{cursor:pointer; font-style:bold; text-decoration:none; color:002c5f;}</style></head><body bgcolor="#ddd5b3" style="font-family:arial, sans-serif; color: #4e3227;">';
	$message[] = '<table id="main" width="100%"><tbody><tr><td colspan="3" bgcolor="#002c5f">';
	$message[] = '<table id="topRow" height="2.5em"><tbody><tr><td colspan="1">';
	$message[] = '<!--THIS WILL BE THE LINK TO THE LOGO--><img src="'. $logo .'" style="float:left;" ></td>';
	$message[] = '<td colspan=2><h2 style="font-family:arial, sans-serif; font-size:2em; color:#ddd5b3; padding-left:.8em; padding-top:.5em; float:left;width:20em;">';
	$message[] = $header .'</h2></td></tr></tbody></table></td></tr>';
	$message[] = '<tr><th width="20%" style="color:#4e3227;font-family:Arial;font-size:1.5em;">Announcements</th><th style="color:#4e3227;font-family:Arial;font-size:1.5em;">Events</th><th width="20%" style="color:#4e3227;font-family:Arial;font-size:1.5em;">Promotions</th></tr>';
	
	$content = accs_get_user_content($user, $type);

	$inSection = false;

	foreach($content as $key => $item){//assumes integer indexed array of items
		//OPEN SECTION
		if(!$inSection){
			$message[] = '<td valign="top"><table id="'.$item->post_type.'" style="color:#4e3227; font-size:.8em; width:100%"><tbody>';
			$inSection = true;
		}			
		

		switch($item->post_type)
		{
			case 'accs_announcement':
				$elements = accs_announcement($item->post_title,  '...' .'</br /><a href=' .get_permalink($item->ID) .' target=_blank> See more</a>' );
				foreach($elements as $e){$message[] = $e;}
				break;
			case 'accs_promo':
				$elements = accs_promotion($item->post_title,  '...' .'<br /><a href=' .get_permalink($item->ID) .' target=_blank> See more</a>' );
				foreach($elements as $e){$message[] = $e;}
				break;
			case 'accs_event':
				$elements = accs_event($item->post_title, $item->post_content);
				foreach($elements as $e){$message[] = $e;}
				break;
			default:
				throw new Exception("Unrecognized Content Type " . $item->post_type);

		 }

		//CLOSE SECTION
		if(isset($content[$key + 1]))
		{
			$nextType = $content[$key + 1]->post_type;
			if($item->post_type != $nextType){
				$message[] = '</tbody></table></td>';
				$inSection = false;
			}

		}else if (!isset($content[$key + 1])) {
			//At End of Array... close off section content
			$message[] = '</tbody></table></td>';
		}
	}

	//Add the last of it.
	$message[] = '</tr><tr><td colspan="3" bgcolor="#002c5f" height="30px;">';
	$message[] = '</td></tr></tbody></table></body></html>';

	return implode($message);
}


function accs_email_settings($type){
	
	$accs = new ACCSCommunicationSystem();
	
	//I assume there is only two types of emails at this
	//point. the daily and then the weekly.

	$subject = 'Unknown Email Type';
	$fromname = 'Rollins ACCS';

	switch($type){
		case 'daily': 
			$subject = 'Good Morning Rollins';
			break;
		case 'weekly': 
			$subject = 'Rollins This Week';
			break;
	}		

	$settings = array(
		'mail-debug'     => $accs->_email_debug,	
		'mail-auth'      => $accs->_email_auth,	
		'mail-secure'    => $accs->_email_secure,	
		'mail-host'      => $accs->_email_host,	
		'mail-port'      => $accs->_email_port,
		'mail-username'  => $accs->_email_username,
		'mail-password'  => $accs->_email_password,		
		'mail-from'      => $accs->_email_from,
		'mail-from-name' => $accs->_email_from_name,
		'mail-subject' 	 => $subject, 
		'mail-alt-body'  => $accs->_email_alt_body,		
		'admin-mail-to'  => $accs->_email_from,
		'admin-mail-subject' => 'Email Process Executed'			
	);

/*
  $settings = array(
                      'mail-debug' => 2,      
                      'mail-auth'  => false,  
                      'mail-secure' => '',    
                      'mail-host' => 'srvmail.rollins.edu',   
                      'mail-port' => 25,
                      'mail-username' => '',
                      'mail-password' => '',          
                      'mail-from' => 'accs-no-reply@rollins.edu',
                      'mail-from-name' => $fromname,
                      'mail-subject' => $subject,     
                      'mail-alt-body' => 'To view the message, please use an HTML compatible email viewer!',                        
                      'admin-mail-to' => 'accsadmin@rollins.edu',
                      'admin-mail-subject' => 'Email Process Executed'                        
                      );

                echo '<pre>';
		print_r($settings);
		echo '</pre>';
*/
	return $settings;
}


function accs_send_email($type, $authcode){

	$ac = get_option('AD_Integration_bulkimport_authcode');

	if ($ac !== $authcode){
		echo'Failed to Send Mail<br/>';
		return;
	}

	$count_success = 0;
	$count_fail = 0;
	$message_list = array();
	
	$message_list[] = 'Email process began - ' .date('r');	
	$settings = accs_email_settings($type);
 	
	$mail = new PHPMailer(true); //defaults to using php "mail()". The true param 
	//means it will throw exceptions on errors, which we need to catch
	$mail->Mailer = 'smtp';
    $mail->SMTPDebug = $settings['mail-debug'];
    $mail->SMTPAuth = $settings['mail-auth'];
    $mail->SMTPSecure = $settings['mail-secure'];
    $mail->Host = $settings['mail-host'];
    $mail->Port = $settings['mail-port'];
    $mail->Username = $settings['mail-username'];
    $mail->Password = $settings['mail-password'];
    $mail->SetFrom($settings['mail-from'], $settings['mail-from-name']);
    $mail->Subject = $settings['mail-subject'];
    $mail->AltBody = $settings['mail-alt-body'];  
    
	$users = get_users();
	foreach($users as $user)
	{
		if($user->ID >1 && $user->ID < 15)
		{
			try{
				echo 'debug: '. $user->user_email .'<br />';
				$mail->ClearAddresses(); //clears anything in the 'to' field
				$mail->AddAddress($user->user_email, $user->display_name);
				$message = accs_get_email_content($user, $type);
				$mail->MsgHTML($message); //should return html				
			
				$mail->Send();
				//echo '<pre>';
				//print_r($mail->Body);
				//echo '</pre>';
			
				$count_success = $count_success + 1;
			} 
			catch (phpmailerException $e)
			{
				$count_fail = $count_fail + 1;
				$message_list[] =trim($e->errorMessage());
				accs_log_event('email error', trim($e->errorMessage()));
			}
			catch (Excepiton $e)
			{
				$count_fail = $count_fail + 1;
				$message_list[] =trim($e->errorMessage());
				accs_log_event('email error', trim($e->errorMessage()));
			}
		}	
	}
	$message_list[] = 'Email process completed - ' .date('r');
	send_admin_notify($count_success, $count_fail, $message_list, $settings, $type);
}
	
function send_admin_notify($count_success, $count_fail, $message_list, $settings, $type){
	$body = array();
	$accs = new ACCSCommunicationSystem();
	
	$mail = new PHPMailer(true); //defaults to using php "mail()". The true param means it will throw exceptions on errors, which we need to catch
	$mail->Mailer = 'smtp';
    $mail->SMTPDebug = $settings['mail-debug'];
    $mail->SMTPAuth = $settings['mail-auth'];
    $mail->SMTPSecure = $settings['mail-secure'];
    $mail->Host = $settings['mail-host'];
    $mail->Port = $settings['mail-port'];
    $mail->Username = $settings['mail-username'];
    $mail->Password = $settings['mail-password'];
    $mail->SetFrom($settings['mail-from'], $settings['mail-from-name']);
    $mail->Subject = $settings['admin-mail-subject'];
	$mail->ClearAddresses(); //clears anything in the 'to' field
	$mail->AddAddress($settings['admin-mail-to'], 'ACCS Admin');

	$body[]   = 'The ' .$type .' email process completed its execution. Below are the process results:<br /><br />';
	$body[] = $message_list[0] .'<br />';
	$body[] = $count_success .' emails were sucessfully sent.<br />';
	$body[] = $count_fail .' emails failed to send.<br />';	
	
	if($count_fail > 0)
	{
		$counter = 0;
		$body[] = '<br /><strong><span style="text-decoration:underline;">List of errors:</span></strong><br />';
		foreach($message_list as $mess)
		{			
			if($counter > 0 && $counter < count($message_list))
			{
				$body[] = $mess .'<br />';
			}		
			$counter = $counter+1;
		}	
		$body[] = '<br />';

	}	

	$url = get_bloginfo('template_url');
	$logo = $url .'/images/Rollins_Horizontal_Small.png';
	$message[] = '<html><head><style>a{cursor:pointer; font-style:bold; text-decoration:none; color:002c5f;}</style></head><body bgcolor="#ddd5b3" style="font-family:arial, sans-serif; color: #4e3227;">';
	$message[] = '<table id="main" width="100%"><tbody><tr><td colspan="3" bgcolor="#002c5f">';
	$message[] = '<table id="topRow" height="2.5em"><tbody><tr><td colspan="1">';
	$message[] = '<!--THIS WILL BE THE LINK TO THE LOGO--><img src="'. $logo .'" style="float:left;" ></td>';
	$message[] = '<td colspan=2><h2 style="font-family:arial, sans-serif; font-size:2em; color:#ddd5b3; padding-left:.8em; padding-top:.5em; float:left;width:20em;">';
	$message[] = 'Email Process Results</h2></td></tr></tbody></table></td></tr>';
	$message[] = '<tr><th width="20%" style="font-family:Arial;font-size:1.5em;">&nbsp;</th><th style="font-family:Arial;font-size:1.5em;">&nbsp;</th><th width="20%" style="font-family:Arial;font-size:1.5em;">&nbsp;</th></tr>';
	$message[] = '<tr><td colspan=3 style="font-family:Arial;font-size:.8em;">';
	$message =  array_merge($message, $body);
	$message[] = '</td></tr>';
	
	$message = implode($message);
	$mail->MsgHTML($message);
	$mail->Send();
	
	//Log the final email
	$accs->accs_log_event($type . ' email process', $mail->Body);
}
?>